<?php

namespace app\admin\controller\newhouse\report;

use app\common\controller\Backend;
use think\Db;

/**
 * 新房报备
 *
 * @icon fa fa-circle-o
 */
class Items extends Backend
{
    
    /**
     * report模型对象
     * @var \app\admin\model\newhouse\report
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\newhouse\report\Items;
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $where1='1=1';
            $who = $this->request->request('who');
            if ($who=='mycreate') {
                $where1 .= ' AND items.create_userid='.$this->auth->id;
            }
            $group = $this->auth->getGroups()[0];
            $group_name=$group['name'];
            if($group_name=='楼盘代理公司' || $group_name=='楼盘开发商'){
                $where1 .= ' and items.cop_id='. $this->auth->cop_id;
            }else if($group_name=='开发商案场负责人' || $group_name='代理商案场负责人'){
                $where1 .= ' and items.create_userid=' . $this->auth->id;
            }else if($group_name=='Admin group'){
                
            }else{
                $this->error(__('You have no permission'));
            }

            $total = $this->model
                    ->with(['newhousecustomer','newhousebuilding','newhousecreateadmin','newhouseverifyadmin'])
                    ->where($where)
                    ->where($where1)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->with(['newhousecustomer','newhousebuilding','newhousecreateadmin','newhouseverifyadmin'])
                    ->where($where)
                    ->where($where1)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            // 取parent值
            $pid_array=[];
            foreach ($list as $row) {
                $row->getRelation('newhousecustomer')->visible(['customer_name','sex_radio','customer_tel','first_house']);
                $row->getRelation('newhousebuilding')->visible(['building_name']);
                $row->getRelation('newhousecreateadmin')->visible(['username','nickname','pid']);
                if (!in_array($row->newhousecreateadmin->pid, $pid_array) && $row->newhousecreateadmin->pid!=0) {
                    $pid_array[] = $row->newhousecreateadmin->pid;
                }
                $row->getRelation('newhouseverifyadmin')->visible(['username','nickname']);
            }
            $pid_str = implode(',', $pid_array);
            $parents = \app\admin\model\Admin::all($pid_str);
            $parent_key_value=[];
            foreach ($parents as $parent) {
                $parent_key_value['_'. $parent->id] = $parent->nickname;
            }
            $list = collection($list)->toArray();

            for ($i=0;$i<sizeof($list);$i++) {
                if ($list[$i]['newhousecreateadmin']['pid'] > 0) {
                    $list[$i]['newhousecreateadmin']['parent_nickname'] = $parent_key_value['_' . $list[$i]['newhousecreateadmin']['pid']];
                } else {
                    $list[$i]['newhousecreateadmin']['parent_nickname']='';
                }
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
    public function mycreate()
    {
        return $this->view->fetch();
    }
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                // 判重
                $list = \app\admin\model\newhouse\report\Items::get(['customer_id'=>$params['customer_id'],'building_id'=>$params['building_id']]);
                if (!empty($list)) {
                    $this->error('报备记录已经存在。');
                } else {
                    $params['create_userid']=$this->auth->id;
                    $params['cop_id']=$this->auth->cop_id;
                    $result = false;
                    Db::startTrans();
                    try {
                        //是否采用模型验证
                        if ($this->modelValidate) {
                            $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                            $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                            $this->model->validateFailException(true)->validate($validate);
                        }
                        $result = $this->model->allowField(true)->save($params);

                        // 客户信息的报备楼盘字段同步修改
                        $model_customer = \app\admin\model\newhouse\customer\Items::get($params['customer_id']);
                        $array=explode(',', $model_customer->building_id);
                        if (!in_array($params['building_id'], $array)) {
                            $array[] = $params['building_id'];
                        }
                        $model_customer->building_id = implode(',', $array);
                        $model_customer->save();
                        
                        Db::commit();
                    } catch (ValidateException $e) {
                        Db::rollback();
                        $this->error($e->getMessage());
                    } catch (PDOException $e) {
                        Db::rollback();
                        $this->error($e->getMessage());
                    } catch (Exception $e) {
                        Db::rollback();
                        $this->error($e->getMessage());
                    }
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error(__('No rows were inserted'));
                    }
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }
    public function add_ajax()
    {
        $customer_id = $this->request->request('customer_id');
        $prepare_visit = $this->request->request('prepare_visit');
        $contents = $this->request->request('contents');
        $building_id = $this->request->request('building_id');
        // 判重
        $list = \app\admin\model\newhouse\report\Items::get(['customer_id'=>$customer_id,'building_id'=>$building_id]);
        if (empty($list)) {
            $model =new  \app\admin\model\newhouse\report\Items;//::get(['customer_id'=>$customer_id,'building_id'=>$building_id]);
            $model->customer_id = $customer_id;
            $model->building_id = $building_id;
            $model->create_userid = $this->auth->id;
            $model->prepare_visit =strtotime($prepare_visit);
            $model->contents = $contents;
            $model->createtime=time();
            $model->save();

            // 客户信息的报备楼盘字段同步修改
            $model_customer = \app\admin\model\newhouse\customer\Items::get($customer_id);
            $array=explode(',', $model_customer->building_id);
            if (!in_array($building_id, $array)) {
                $array[] = $building_id;
            }
            $model_customer->building_id = implode(',', $array);
            $model_customer->save();
            
            return json(['success'=>true]);
        } else {
            return json(['success'=>false]);
        }
    }
    public function sync($customer_id, $buildings)
    {
        $building_array=explode(',', $buildings);
        foreach ($building_array as $key=>$building_id) {
            if (empty($building_id) || $building_id=='0') {
                continue;
            }
            $has = \app\admin\model\newhouse\report\Items::get(['building_id'=>$building_id,'customer_id'=>$customer_id]);
            if (empty($has)) {
                $has=new \app\admin\model\newhouse\report\Items;
                $has->customer_id=$customer_id;
                $has->building_id=$building_id;
                $has->create_userid=$this->auth->id;
                $has->update_userid=$this->auth->id;
                $has->createtime=time();
                $has->save();
            } else {
                $has->updatetime=time();
                $has->save();
            }
        }
      
        $db_list=\app\admin\model\newhouse\report\Items::all(['customer_id'=>$customer_id]);
        if (!empty($db_list)) {
            foreach ($db_list as $key=>$value) {
                if (!in_array($value->building_id, $building_array)) {
                    $value->delete();
                }
            }
        }
    }
    /**
      * 审核、查看
      */
    public function view($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $customer_model = \app\admin\model\newhouse\customer\Items::get($row->customer_id);

        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $params['verify_time'] = time();  // 审核时间
                $params['verify_userid'] = $this->auth->id;
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    // 修改customer信息
                    $customer_item_model = \app\admin\model\newhouse\customer\Items::get($row->customer_id);
                    $customer_item_model->verify_state=$params['verify_state'];
                    $customer_item_model->verify_time=time();
                    $customer_item_model->verify_userid=$this->auth->id;
                    $customer_item_model->verify_friend=$params['verify_friend'];
                    $customer_item_model->verify_mem=$params['verify_mem'];
                    $customer_item_model->save();

                    $this->sync($row->customer_id, $params['building_id']);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $follow_model = new \app\admin\model\newhouse\customer\Follow;
        $follow_list=$follow_model->where(['customer_id'=>$ids])->select();
        // 查找相同号码的客户
        $customer_same_mobile = \app\admin\model\newhouse\customer\Items::where('customer_tel', $customer_model->customer_tel)->where('id', '<>', $customer_model->id)->select();
        $customer_same_mobile_ids =[];
        foreach ($customer_same_mobile as $key=>$value) {
            if ($value->id != $customer_model->id) {
                $customer_same_mobile_ids[] = $value->id;
            }
        }
        $customer_same_mobile_ids_str = implode(',', $customer_same_mobile_ids);
        
        // 查找相同号码的报备记录，但reportid和当前值不一样的
        $history = \app\admin\model\newhouse\report\Items::where('customer_id', 'in', $customer_same_mobile_ids_str)->where('building_id', $row->building_id)->with('newhousecreateadmin')->select();

        $this->view->assign("row", $row);
        $this->view->assign("customer_model", $customer_model);
        $this->view->assign("follow_list", $follow_list);
        $this->view->assign('history', $history);
        $this->view->assign('historycount',sizeof($history));

        $parent_admin_model = \app\admin\model\Admin::get($row->newhousecreateadmin->pid);
        if (empty($parent_admin_model->nickname)) {
            $parent_nickname='';
        } else {
            $parent_nickname ="[ $parent_admin_model->nickname ]";
        }
        $this->view->assign('parent_nickname', $parent_nickname);
        return $this->view->fetch();
    }
    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            
            $count = 0;
            Db::startTrans();
            try {
                // 把customer_model里buidling_id字段对应的值删除
                $report_item_model=\app\admin\model\newhouse\report\Items::get($ids);
                $customer_model = \app\admin\model\newhouse\customer\Items::get($report_item_model->customer_id);
                if (!empty($customer_model)) {
                    $building_array = explode(',', $customer_model->building_id);
                    foreach ($building_array as $k1=>$v1) {
                        if ($v1==$report_item_model->building_id) {
                            unset($building_array[$k1]);
                        }
                    }
                    $customer_model->building_id = implode(',', $building_array);
                    $customer_model->save();
                }

                foreach ($list as $k => $v) {
                    $count += $v->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
}
